#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <GL/glew.h>
#include <GL/glfw3.h>

GLFWwindow g_window;
GLuint g_path;

void OpenGLDebugOutput(GLenum source, GLenum type, GLuint id,
                       GLenum severity, GLsizei length,
                       const GLchar *message, GLvoid *param) {
  fprintf(stderr, "%s\n", message);
}

void Keyboard(GLFWwindow win, int key, int action) {
  if (action != GLFW_PRESS) return;
  switch (key) {
    case GLFW_KEY_ESCAPE: glfwCloseWindow(g_window); break;
  }
}

int main(int argc, char *argv[]) {
  glfwInit();
  glfwSetKeyCallback(Keyboard);

  glfwOpenWindowHint(GLFW_RED_BITS, 8);
  glfwOpenWindowHint(GLFW_GREEN_BITS, 8);
  glfwOpenWindowHint(GLFW_BLUE_BITS, 8);
  glfwOpenWindowHint(GLFW_DEPTH_BITS, 24);
  glfwOpenWindowHint(GLFW_STENCIL_BITS, 8);
  glfwOpenWindowHint(GLFW_WINDOW_RESIZABLE, 0);
  glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
  g_window = glfwOpenWindow(300, 300, GLFW_WINDOWED, "Sketch 1", NULL);

  glfwSwapInterval(0);
  glewInit();
  glDebugMessageCallbackARB(OpenGLDebugOutput, NULL);

  glMatrixLoadIdentityEXT(GL_PROJECTION);
  glMatrixOrthoEXT(GL_PROJECTION, 0.0, 300.0, 300.0, 0.0, -1.0, 1.0);

  while (glfwIsWindow(g_window)) {
    glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glMatrixLoadIdentityEXT(GL_MODELVIEW);
    srand(0);

    int totalPts = 1000;
    float steps = totalPts+1;
    int totalRows = 50;
    // needs to be < = 300
    int rowShift = 300/totalRows;
    float rowNudge = -.4;
    float rowHop = 0;
    int randNudge = 5;
    for (int i=rowShift; i<300; i+=rowShift ){
      for (int j=1; j<steps; j++){
        rowHop-=rowNudge;
        if (j % (1 + (int)(rand()%randNudge)) == 0){
          rowNudge*=-1;
        }
        glBegin(GL_POINTS);
        glVertex2i((300/steps)*j, i+rowHop);
        glEnd();
      }
    }

    glfwSwapBuffers();
    glfwPollEvents();
  }
  glfwTerminate();

  return 0;
}
